layui.extend({
    treetable: '../../lib/treetable/treetable'
}).define(['baseUtil', 'treetable'], function (exports) {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        layer = layui.layer,
        baseUtil = layui.baseUtil,
        treetable = layui.treetable;

    var treeTable = {
        /**
         * 初始化TreeTable
         */
        initTreeTable: function (url, cols) {
            treeTable.initTreeTableData(url, cols);
            treeTable.initTreeTableListener(url, cols);
        },
        /**
         * 初始化TreeTable数据
         */
        initTreeTableData: function (url, cols, where) {
            var index = layer.load(2);
            treetable.render({
                treeColIndex: 1,
                treeSpid: -1,
                treeIdName: 'id',
                treePidName: 'parentId',
                elem: '#layuiTable',
                url: url,
                headers: { 'token': getAccessToken() },
                where: where,
                page: false,
                cols: [cols],
                done: function (result) {
                    layer.close(index);
                    if (result.code === 2) {
                        requireLogin();
                    }
                }
            });
        },
        /**
         * 初始化TreeTable监听
         */
        initTreeTableListener: function (urls, cols, wheres) {
            //展开树
            $('#expandAll').bind('click', function () {
                treetable.expandAll('#layuiTable');
            });

            //收起树
            $('#foldAll').bind('click', function () {
                treetable.foldAll('#layuiTable');
            });

            //搜索
            form.on('submit(treeTableSearchBtn)', function (data) {
                treeTable.initTreeTableData(urls, cols, data.field);
                return false;
            });
            //操作
            table.on('tool(treeTableTool)', function (obj) {
                var event = obj.event;
                var id = obj.data.id;
                var url = this.getAttribute('data-url');
                if (event === 'add') {
                    baseUtil.iframe('添加', url + '?parentId=' + id);
                } else if (event === 'edit') {
                    if (isBlank(obj.data.parentId)) {
                        baseUtil.iframe('编辑', url + '?id=' + id);
                    } else {
                        baseUtil.iframe('编辑', url + '?id=' + id + '&parentId=' + obj.data.parentId);
                    }
                } else if (event === 'delete') {
                    baseUtil.confirm('您确定要删除选中项?', '3', function () {
                        baseUtil.doPostData(url, { id: id }, function () {
                            treeTable.initTreeTableData(urls, cols, wheres);
                        });
                    });
                }
            });
        }
    };
    exports('treeTable', treeTable);
});
